require_dependency "search" 
class Comment < ActiveRecord::Base
  belongs_to            :user
  belongs_to            :photo
  belongs_to            :video
  validates_presence_of :text
  validates_presence_of :user
  validate              :assigned_to_either_photo_or_video
  validate              :assigned_to_only_a_photo_or_a_video_and_not_both
  searches_on           :text
  
  before_save           :sanitize_text!
  
  def sanitized_text
    self.text.gsub(/<\/?\w+((\s+\w+(\s*=\s*(?:".*?"|'.*?'|[^'">\s]+))?)+\s*|\s*)\/?>/,  "")
  end
  
  def is_private?
    self.for_photo? ? self.photo.is_private? : self.video.is_private?
  end
  
  def is_invisible?
    self.for_photo? ? self.photo.is_invisible? : self.video.is_invisible?
  end
  
  def assigned_to_either_photo_or_video
    (!self.video.nil? or !self.photo.nil?) ? true : false
  end
  
  def assigned_to_only_a_photo_or_a_video_and_not_both
    (self.video and self.photo) ? false : true
  end
  
  def authorized_to_modify?(current_user)
    (current_user == self.user) ? true : false
  end
  
  def for_a?
    return "photo" if self.photo
    return "video" if self.video
  end
  
  def for_video?
    self.video ? true : false
  end
  
  def for_photo?
    self.photo ? true : false
  end
protected
  def sanitize_text!
    self.text.gsub!(/<\/?\w+((\s+\w+(\s*=\s*(?:".*?"|'.*?'|[^'">\s]+))?)+\s*|\s*)\/?>/,  "")
  end
end
